import 'package:flutter/material.dart';
import 'page_flip_types.dart';

/// 页面容器 - 用于复用页面Widget，避免重复创建
class PageContainer extends StatefulWidget {
  final int containerId; // 容器ID (0, 1, 2)
  final PageBuilder pageBuilder;
  final int? currentPageIndex; // 当前显示的页面索引
  final VoidCallback? onPageBuilt; // 页面构建完成回调

  const PageContainer({
    super.key,
    required this.containerId,
    required this.pageBuilder,
    this.currentPageIndex,
    this.onPageBuilt,
  });

  @override
  State<PageContainer> createState() => _PageContainerState();
}

class _PageContainerState extends State<PageContainer> {
  Widget? _cachedPage;
  int? _cachedPageIndex;

  @override
  void initState() {
    super.initState();
    _buildPageIfNeeded();
  }

  @override
  void didUpdateWidget(PageContainer oldWidget) {
    super.didUpdateWidget(oldWidget);

    // 如果页面索引发生变化，需要重新构建页面
    if (oldWidget.currentPageIndex != widget.currentPageIndex) {
      _buildPageIfNeeded();
    }
  }

  void _buildPageIfNeeded() {
    if (widget.currentPageIndex != null &&
        widget.currentPageIndex != _cachedPageIndex) {
      try {
        _cachedPage = widget.pageBuilder(widget.currentPageIndex!);
        _cachedPageIndex = widget.currentPageIndex;

        // 通知页面构建完成
        WidgetsBinding.instance.addPostFrameCallback((_) {
          widget.onPageBuilt?.call();
        });
      } catch (e) {
        // 构建失败时显示错误页面
        _cachedPage = _buildErrorPage(widget.currentPageIndex!, e);
        _cachedPageIndex = widget.currentPageIndex;
      }
    }
  }

  Widget _buildErrorPage(int index, dynamic error) {
    return Container(
      color: Colors.red[100],
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error, size: 64, color: Colors.red),
            const SizedBox(height: 16),
            Text(
              '页面 $index 加载失败',
              style: const TextStyle(fontSize: 18, color: Colors.red),
            ),
            const SizedBox(height: 8),
            Text(
              error.toString(),
              style: const TextStyle(fontSize: 12, color: Colors.red),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 如果没有页面索引或页面未构建，显示空白
    if (widget.currentPageIndex == null || _cachedPage == null) {
      return Container(
        color: Colors.transparent,
        child: const SizedBox.expand(),
      );
    }

    return _cachedPage!;
  }
}

/// 页面容器管理器 - 管理3个页面容器的状态和数据
class PageContainerManager {
  static const int containerCount = 3;

  // 3个容器的页面索引映射
  final List<int?> _containerPageIndexes = List.filled(containerCount, null);

  // 当前页面索引
  int _currentPageIndex = 0;

  // 页面总数
  final int pageCount;

  PageContainerManager({required this.pageCount}) {
    // 初始化时更新容器映射
    _updateContainerMapping();
  }

  /// 获取当前页面索引
  int get currentPageIndex => _currentPageIndex;

  /// 设置当前页面索引并更新容器映射
  void setCurrentPageIndex(int index) {
    if (index < 0 || index >= pageCount) return;

    _currentPageIndex = index;
    _updateContainerMapping();
  }

  /// 更新容器映射关系
  void _updateContainerMapping() {
    // 容器0：前一页 (currentIndex - 1)
    // 容器1：当前页 (currentIndex)
    // 容器2：下一页 (currentIndex + 1)

    _containerPageIndexes[0] =
        _currentPageIndex > 0 ? _currentPageIndex - 1 : null;
    _containerPageIndexes[1] = _currentPageIndex;
    _containerPageIndexes[2] =
        _currentPageIndex < pageCount - 1 ? _currentPageIndex + 1 : null;
  }

  /// 获取指定容器应该显示的页面索引
  int? getContainerPageIndex(int containerId) {
    if (containerId < 0 || containerId >= containerCount) return null;
    return _containerPageIndexes[containerId];
  }

  /// 获取指定页面索引对应的容器ID
  int? getContainerIdForPage(int pageIndex) {
    for (int i = 0; i < containerCount; i++) {
      if (_containerPageIndexes[i] == pageIndex) {
        return i;
      }
    }
    return null;
  }

  /// 获取所有容器的页面索引映射
  List<int?> getAllContainerPageIndexes() {
    return List.from(_containerPageIndexes);
  }

  /// 重置所有容器
  void reset() {
    _containerPageIndexes.fillRange(0, containerCount, null);
    _currentPageIndex = 0;
  }
}
